import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { nanoid } from 'nanoid/non-secure'
import {
  getBookmarkData,
  getCategories,
  createCategory,
  updateCategory as apiUpdateCategory,
  deleteCategory as apiDeleteCategory,
  getBookmarks,
  createBookmark,
  updateBookmark as apiUpdateBookmark,
  deleteBookmark as apiDeleteBookmark,
  importBookmarkData,
  updateCategoriesSort,
  updateBookmarksSort
} from '@/utils/api'
import { useUserStore } from './user'
import defaultData from './defaultData.json'

export const useBookmarkStore = defineStore(
  'bookmark',
  () => {
    // 状态
    const categories = ref([])
    const bookmarks = ref([])
    const selectedCategory = ref(['all'])
    const searchText = ref('')
    const isSearchFocused = ref(false)
    const loading = ref(false)
    const initialized = ref(false)

    // 模态框状态管理
    const isBookmarkModalOpen = ref(false)
    const isCategoryModalOpen = ref(false)

    // 获取用户store
    const userStore = useUserStore()

    // 数据转换函数：后端数据转前端格式
    const transformCategoryFromAPI = (apiCategory) => {
      return {
        id: apiCategory.id,
        key: apiCategory.key,
        label: apiCategory.label,
        sortOrder: apiCategory.sort_order,
        createdAt: apiCategory.created_at,
        updatedAt: apiCategory.updated_at
      }
    }

    const transformBookmarkFromAPI = (apiBookmark) => {
      return {
        id: apiBookmark.id,
        title: apiBookmark.title,
        url: apiBookmark.url,
        description: apiBookmark.description,
        categoryId: apiBookmark.category_id,
        userId: apiBookmark.user_id,
        sortOrder: apiBookmark.sort_order,
        createdAt: apiBookmark.created_at,
        updatedAt: apiBookmark.updated_at
      }
    }

    // 数据转换函数：前端数据转后端格式
    const transformCategoryToAPI = (frontendCategory) => {
      return {
        key: frontendCategory.key,
        label: frontendCategory.label,
        sortOrder: frontendCategory.sortOrder || 0
      }
    }

    const transformBookmarkToAPI = (frontendBookmark) => {
      return {
        title: frontendBookmark.title,
        url: frontendBookmark.url,
        description: frontendBookmark.description,
        categoryId: frontendBookmark.categoryId,
        sortOrder: frontendBookmark.sortOrder || 0
      }
    }

    // 计算属性
    const filteredBookmarks = computed(() => {
      let result = bookmarks.value

      // 分类过滤
      if (selectedCategory.value[0] !== 'all') {
        result = result.filter((item) => {
          if (!userStore.isAuthenticated) {
            // 离线模式：需要通过分类ID找到对应的key进行比较
            const category = categories.value.find((c) => c.id === item.categoryId)
            return category?.key === selectedCategory.value[0]
          } else {
            // 在线模式：需要通过分类ID找到key
            const categoryKey = categories.value.find((c) => c.id === item.categoryId)?.key
            return categoryKey === selectedCategory.value[0]
          }
        })
      }

      // 搜索过滤
      if (searchText.value) {
        const search = searchText.value.toLowerCase()
        result = result.filter((item) => item.title.toLowerCase().includes(search) || item.url.toLowerCase().includes(search) || item.description?.toLowerCase().includes(search))
      }

      return result
    })

    // 初始化数据
    const initializeData = async () => {
      if (!userStore.isAuthenticated) {
        // 离线模式：检查是否有持久化的数据
        const hasValidData = categories.value.length > 0 && bookmarks.value.length > 0

        if (!hasValidData) {
          // 如果没有持久化的数据，使用默认数据
          categories.value = defaultData.categories.map((cat) => ({
            ...cat,
            id: cat.id, // 使用原有的数字ID
            key: cat.key // 保持原有的key
          }))
          bookmarks.value = defaultData.bookmarks.map((bookmark) => ({
            ...bookmark,
            categoryId: bookmark.categoryId, // 保持原有的数字ID格式
            id: bookmark.id || nanoid() // 确保有ID
          }))
        } else {
          // 有持久化数据，验证数据完整性
          // 确保"全部"分类存在
          const hasAllCategory = categories.value.some((c) => c.key === 'all')
          if (!hasAllCategory) {
            categories.value.unshift({
              id: nanoid(),
              key: 'all',
              label: '全部',
              sortOrder: 0
            })
          }

          // 验证所有书签的分类关联
          const validCategoryIds = new Set(categories.value.map((c) => c.id))
          bookmarks.value = bookmarks.value.filter((bookmark) => validCategoryIds.has(bookmark.categoryId))
        }

        // 验证和修复数据
        validateAndFixData()

        initialized.value = true
        return
      }

      loading.value = true
      try {
        const response = await getBookmarkData()

        // 转换后端数据为前端格式
        categories.value = response.data.categories.map(transformCategoryFromAPI)
        bookmarks.value = response.data.bookmarks.map(transformBookmarkFromAPI)

        // 数据验证：检查书签的分类关联是否有效
        const categoryIds = new Set(categories.value.map((c) => c.id))

        const validBookmarks = []
        const invalidBookmarks = []

        bookmarks.value.forEach((bookmark) => {
          if (!categoryIds.has(bookmark.categoryId)) {
            invalidBookmarks.push(bookmark)
          } else {
            validBookmarks.push(bookmark)
          }
        })

        if (invalidBookmarks.length > 0) {
        }

        bookmarks.value = validBookmarks

        // 确保"全部"分类在最前面
        const allCategoryIndex = categories.value.findIndex((c) => c.key === 'all')
        if (allCategoryIndex > 0) {
          const allCategory = categories.value.splice(allCategoryIndex, 1)[0]
          categories.value.unshift(allCategory)
        } else if (allCategoryIndex === -1) {
          // 如果后端没有"全部"分类，前端添加一个虚拟的
          categories.value.unshift({ key: 'all', label: '全部', id: 'virtual-all' })
        }

        initialized.value = true
      } catch (error) {
        // 出错时使用默认数据
        categories.value = defaultData.categories.map((cat) => ({
          ...cat,
          id: nanoid()
        }))
        bookmarks.value = defaultData.bookmarks
      } finally {
        loading.value = false
      }
    }

    // 方法：分类管理
    const addCategory = async (name) => {
      if (!userStore.isAuthenticated) {
        // 离线模式
        const newCategory = {
          id: nanoid(),
          key: nanoid(),
          label: name,
          sortOrder: categories.value.length
        }
        categories.value.push(newCategory)
        validateAndFixData() // 验证数据
        return newCategory
      }

      try {
        // 计算新分类的排序序号（跳过"全部"分类）
        const userCategories = categories.value.filter((c) => c.key !== 'all')
        const maxSortOrder = userCategories.length > 0 ? Math.max(...userCategories.map((c) => c.sortOrder || 0)) : 0

        const categoryData = {
          key: nanoid(),
          label: name,
          sortOrder: maxSortOrder + 1
        }

        const response = await createCategory(categoryData)
        const newCategory = {
          id: response.data.id,
          key: categoryData.key,
          label: name,
          sortOrder: categoryData.sortOrder
        }

        categories.value.push(newCategory)
        return newCategory
      } catch (error) {
        throw error
      }
    }

    const updateCategory = async (category) => {
      if (!userStore.isAuthenticated) {
        // 离线模式
        const index = categories.value.findIndex((c) => c.key === category.key)
        if (index !== -1) {
          categories.value[index] = { ...categories.value[index], label: category.label }
        }
        return
      }

      try {
        const categoryData = transformCategoryToAPI(category)
        await apiUpdateCategory(category.id, categoryData)

        const index = categories.value.findIndex((c) => c.key === category.key)
        if (index !== -1) {
          categories.value[index] = { ...categories.value[index], label: category.label }
        }
      } catch (error) {
        throw error
      }
    }

    const deleteCategory = async (category) => {
      if (!userStore.isAuthenticated) {
        // 离线模式
        const index = categories.value.findIndex((c) => c.key === category.key)
        if (index !== -1) {
          // 查找一个替代分类（除了要删除的分类和'all'分类）
          const remainingCategories = categories.value.filter((c) => c.key !== category.key && c.key !== 'all')
          const fallbackCategoryKey = remainingCategories.length > 0 ? remainingCategories[0].key : null

          if (fallbackCategoryKey) {
            // 将该分类下的书签移动到替代分类
            bookmarks.value.forEach((bookmark) => {
              if (bookmark.categoryId === category.key) {
                bookmark.categoryId = fallbackCategoryKey
              }
            })
          } else {
            // 如果没有其他分类，删除该分类下的所有书签
            bookmarks.value = bookmarks.value.filter((bookmark) => bookmark.categoryId !== category.key)
          }

          categories.value.splice(index, 1)

          // 如果当前选中的是被删除的分类，切换到默认分类
          if (selectedCategory.value[0] === category.key) {
            selectedCategory.value = ['all']
          }
        }
        return
      }

      try {
        await apiDeleteCategory(category.id)

        const index = categories.value.findIndex((c) => c.key === category.key)
        if (index !== -1) {
          // API会自动处理分类下的书签，这里只需要删除分类
          categories.value.splice(index, 1)
          // 如果当前选中的是被删除的分类，切换到默认分类
          if (selectedCategory.value[0] === category.key) {
            selectedCategory.value = ['all']
          }
        }
      } catch (error) {
        throw error
      }
    }

    // 方法：书签管理
    const addBookmark = async (bookmark) => {
      if (!userStore.isAuthenticated) {
        // 离线模式 - 验证分类是否存在
        const category = categories.value.find((c) => c.key === bookmark.categoryId)
        if (!category || category.key === 'all') {
          throw new Error('请选择有效的分类')
        }

        const newBookmark = {
          id: nanoid(),
          title: bookmark.title,
          url: bookmark.url,
          description: bookmark.description || '',
          categoryId: bookmark.categoryId, // 保持key格式，与离线数据一致
          sortOrder: bookmarks.value.length
        }
        bookmarks.value.push(newBookmark)
        validateAndFixData() // 验证数据
        return newBookmark
      }

      try {
        // 找到分类的数据库ID
        const category = categories.value.find((c) => c.key === bookmark.categoryId)
        const categoryDbId = category?.id

        if (!categoryDbId || categoryDbId === 'all') {
          throw new Error('请选择有效的分类')
        }

        const bookmarkData = {
          ...transformBookmarkToAPI(bookmark),
          categoryId: categoryDbId,
          sortOrder: bookmarks.value.length
        }

        const response = await createBookmark(bookmarkData)
        const newBookmark = {
          id: response.data.id,
          title: bookmark.title,
          url: bookmark.url,
          description: bookmark.description,
          categoryId: categoryDbId,
          sortOrder: bookmarkData.sortOrder
        }

        bookmarks.value.push(newBookmark)
        return newBookmark
      } catch (error) {
        throw error
      }
    }

    const updateBookmark = async (id, data) => {
      if (!userStore.isAuthenticated) {
        // 离线模式 - 验证分类是否存在
        if (data.categoryId) {
          const category = categories.value.find((c) => c.key === data.categoryId)
          if (!category || category.key === 'all') {
            throw new Error('请选择有效的分类')
          }
        }

        const index = bookmarks.value.findIndex((item) => item.id === id)
        if (index !== -1) {
          bookmarks.value[index] = {
            ...bookmarks.value[index],
            ...data,
            // 保持key格式，与离线数据一致
            categoryId: data.categoryId || bookmarks.value[index].categoryId
          }
        }
        return
      }

      try {
        // 找到分类的数据库ID
        const category = categories.value.find((c) => c.key === data.categoryId)
        const categoryDbId = category?.id

        if (!categoryDbId || categoryDbId === 'all') {
          throw new Error('请选择有效的分类')
        }

        const bookmarkData = {
          ...transformBookmarkToAPI(data),
          categoryId: categoryDbId
        }

        await apiUpdateBookmark(id, bookmarkData)

        const index = bookmarks.value.findIndex((item) => item.id === id)
        if (index !== -1) {
          bookmarks.value[index] = {
            ...bookmarks.value[index],
            ...data,
            categoryId: categoryDbId
          }
        }
      } catch (error) {
        throw error
      }
    }

    const deleteBookmark = async (id) => {
      if (!userStore.isAuthenticated) {
        // 离线模式
        const index = bookmarks.value.findIndex((item) => item.id === id)
        if (index !== -1) {
          bookmarks.value.splice(index, 1)
        }
        return
      }

      try {
        await apiDeleteBookmark(id)

        const index = bookmarks.value.findIndex((item) => item.id === id)
        if (index !== -1) {
          bookmarks.value.splice(index, 1)
        }
      } catch (error) {
        throw error
      }
    }

    // 导入数据
    const importData = async (data) => {
      if (!userStore.isAuthenticated) {
        // 离线模式
        const allCategory = categories.value.find((c) => c.key === 'all')
        categories.value = [allCategory, ...data.categories.filter((c) => c.key !== 'all')]
        bookmarks.value = data.bookmarks
        return
      }

      try {
        await importBookmarkData(data)
        // 重新加载数据
        await initializeData()
      } catch (error) {
        throw error
      }
    }

    // 排序功能
    const sortCategories = async (newCategories) => {
      categories.value = newCategories

      if (userStore.isAuthenticated) {
        try {
          // 过滤掉"全部"分类，只更新用户创建的分类
          const userCategories = newCategories.filter((c) => c.key !== 'all')
          // 重新分配排序序号
          const categoriesWithNewOrder = userCategories.map((category, index) => ({
            ...category,
            sortOrder: index + 1 // 从1开始，因为0保留给"all"分类
          }))

          await updateCategoriesSort(categoriesWithNewOrder)
        } catch (error) {}
      }
    }

    const sortBookmarks = async (newBookmarks) => {
      // 获取当前分类
      const currentCategoryKey = selectedCategory.value[0]

      // 为拖拽后的书签重新分配sortOrder
      const bookmarksWithOrder = newBookmarks.map((bookmark, index) => ({
        ...bookmark,
        sortOrder: index
      }))

      if (currentCategoryKey === 'all') {
        // 如果是全部分类，直接更新所有书签
        bookmarks.value = bookmarksWithOrder
      } else {
        // 如果是其他分类，只更新当前分类的书签顺序
        if (!userStore.isAuthenticated) {
          // 离线模式：使用key格式过滤
          const otherBookmarks = bookmarks.value.filter((b) => b.categoryId !== currentCategoryKey)
          bookmarks.value = [...otherBookmarks, ...bookmarksWithOrder]
        } else {
          // 在线模式：使用数据库ID过滤
          const currentCategoryId = categories.value.find((c) => c.key === currentCategoryKey)?.id
          const otherBookmarks = bookmarks.value.filter((b) => b.categoryId !== currentCategoryId)
          bookmarks.value = [...otherBookmarks, ...bookmarksWithOrder]
        }
      }

      if (userStore.isAuthenticated) {
        try {
          await updateBookmarksSort(bookmarksWithOrder)
        } catch (error) {}
      }
    }

    // 数据验证和修复函数
    const validateAndFixData = () => {
      if (!userStore.isAuthenticated) {
        // 离线模式：确保所有书签都有正确的sortOrder
        bookmarks.value = bookmarks.value.map((bookmark, index) => ({
          ...bookmark,
          sortOrder: bookmark.sortOrder !== undefined ? bookmark.sortOrder : index,
          id: bookmark.id || nanoid()
        }))

        // 确保所有分类都有正确的sortOrder和id
        categories.value = categories.value.map((category, index) => ({
          ...category,
          sortOrder: category.sortOrder !== undefined ? category.sortOrder : index,
          id: category.id || nanoid()
        }))
      }
    }

    // 强制重新初始化数据
    const forceReinitialize = async () => {
      initialized.value = false
      await initializeData()
    }

    // 重置数据到默认状态
    const resetToDefault = () => {
      categories.value = defaultData.categories
      bookmarks.value = defaultData.bookmarks
      selectedCategory.value = ['all']
      searchText.value = ''
      initialized.value = false
    }

    // 监听用户登录状态变化
    watch(
      () => userStore.isAuthenticated,
      async (newAuth, oldAuth) => {
        // 当从登录状态变为未登录状态时，重新初始化为离线模式
        if (oldAuth === true && newAuth === false) {
          // 用户退出登录，切换到离线模式
          initialized.value = false
          loading.value = false

          // 清空在线数据，强制重新加载本地数据
          categories.value = []
          bookmarks.value = []

          // 重新初始化数据，这会从本地存储或默认数据加载
          await initializeData()

          // 重置选中分类为"全部"
          selectedCategory.value = ['all']
        }
        // 当从未登录状态变为登录状态时，重新初始化为在线模式
        else if (oldAuth === false && newAuth === true) {
          // 用户登录，切换到在线模式
          initialized.value = false
          await initializeData()
        }
      },
      { immediate: false } // 不立即执行，只监听变化
    )

    return {
      // 状态
      categories,
      bookmarks,
      selectedCategory,
      searchText,
      isSearchFocused,
      loading,
      initialized,
      isBookmarkModalOpen,
      isCategoryModalOpen,
      // 计算属性
      filteredBookmarks,
      // 方法
      initializeData,
      addBookmark,
      updateBookmark,
      deleteBookmark,
      addCategory,
      updateCategory,
      deleteCategory,
      importData,
      resetToDefault,
      sortCategories,
      sortBookmarks,
      validateAndFixData,
      forceReinitialize
    }
  },
  {
    persist: {
      // 持久化UI状态和离线数据
      paths: ['selectedCategory', 'searchText', 'categories', 'bookmarks'],
      // 根据登录状态决定是否持久化数据
      beforeRestore: (context) => {
        // 这里会在store恢复前调用，我们在initializeData中处理数据逻辑
      }
    }
  }
)
